package com.css.apps.base.menu.service;

import java.util.List;
import java.util.Map;

import com.css.apps.base.menu.model.SMenu;
import com.css.common.plugins.impl.AbstractConfigurablePlugin;
import com.css.core.model.IUser;
import com.css.core.model.tree.Tree;
import com.css.core.model.tree.TreeCache;
import com.css.core.model.tree.TreeNode;
import com.css.db.config.ConfigurationManager;
import com.css.db.query.QueryCache;
import com.css.util.StringHelper;
import com.css.webbase.WebBaseUtil;
import com.css.webbase.menu.MenuItem;

public class IdsDBMenuProvider extends AbstractConfigurablePlugin implements IMenuProvider {
	
	private boolean cached = true;
	private String cacheName = "_user_menu_cache/";
	@SuppressWarnings("unused")
	private boolean ignoreOneTop = false;

	@Override
	protected void doConfig(Map<String, String> configMap) {
		if (configMap == null)
			return;
		if ("false".equals(configMap.get("cache"))) {
			cached = false;
		}
		if ("true".equals(configMap.get("ignoreOneTop"))) {
			ignoreOneTop = true;
		}
	}

	@Override
	public List<MenuItem> getAllMenu(IUser user, String sysId) {
		java.util.List<MenuItem> items = null;
		if (cached) {
			items = getCachedListItem(user, sysId);
			if (items != null)
				return items;
		}
		Tree tree = new TreeCache(SMenu.class);
		// 根节点
		List<TreeNode> roots = tree.getRoot();
		if (roots != null && roots.size() != 0) {
			items = new java.util.ArrayList<MenuItem>();
			for (TreeNode root : tree.getRoot()) {
				int level = 1;
				MenuItem mi = transpass(root, level, user, sysId);
				if (mi != null)
					items.add(mi);
			}
			// if(items.size()==1 && ignoreOneTop){
			// MenuItem mi=items.get(0);
			// if(StringHelper.isEmptyByTrim(mi.getPath()))
			// items = mi.getMenus();
			// }
			if (cached)
				cacheListItem(user, sysId, items);
		}
		return items;
	}

	/**
	 * 遍历菜单树，获取系统菜单
	 * 
	 * @param menuItem
	 * @param node
	 * @param level
	 * @param funcCodes
	 */
	private MenuItem transpass(TreeNode node, int level, IUser user, String sysId) {
		// 获取所有子节点
		List<TreeNode> sMenuNodes = node.getChildren();
		String curMenuId = node.getNodeId();
		MenuItem menuItem = new MenuItem();
		SMenu menu = QueryCache.get(SMenu.class, curMenuId);
		if (menu != null && "1".equals(menu.getOpenFlag()) && sysId.equals(menu.getSysId())) {
			String funcId = menu.getFuncId();
			String url = menu.getUrl();
			/*
			 * Set<String> funcCodes = user.getFunctions(); if(isSecured &&
			 * !(StringHelper.isEmptyByTrim(funcId) &&
			 * StringHelper.isEmptyByTrim(url)) && !funcCodes.contains(funcId))
			 * return null;
			 */
			// 暂时修改，for测试
			if (StringHelper.isEmptyByTrim(funcId)) {
				System.out.println("funcId is null");
			}
			if (StringHelper.isEmptyByTrim(url)) {
				System.out.println("url is null");
			}
			if (!WebBaseUtil.hasPrivilege(user, funcId)) {
				System.out.println(user.getLoginName() + " hasn't privilige");
			}
			if (!(StringHelper.isEmptyByTrim(funcId) && StringHelper.isEmptyByTrim(url))
					&& !WebBaseUtil.hasPrivilege(user, funcId))
				return null;
			menuItem.setId(menu.getMenuId());
			menuItem.setIcon(menu.getIcon());
			menuItem.setLevel(level);
			menuItem.setName(menu.getMenuName());
			menuItem.setOpenIcon(menu.getIcon());
			menuItem.setPath(url);
			menuItem.setFuncode(menu.getFuncId());
			menuItem.setParentId(menu.getParentId());
			menuItem.setVisible(true);
			if (sMenuNodes.isEmpty())
				menuItem.setIsLast(true);
			else
				menuItem.setIsLast(false);

		} else
			return null;

		if (sMenuNodes != null && !sMenuNodes.isEmpty()) {
			for (TreeNode node1 : sMenuNodes) {
				MenuItem mi = transpass(node1, level + 1, user, sysId);
				if (mi != null)
					menuItem.getMenus().add(mi);
			}
			String funcId = menu.getFuncId();
			String url = menu.getUrl();

			if (StringHelper.isEmptyByTrim(funcId) && StringHelper.isEmptyByTrim(url) && menuItem.getMenus().isEmpty())
				return null;
		}
		return menuItem;
	}

	/**
	 * 从缓存中获取用户菜单
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<MenuItem> getCachedListItem(IUser user, String sysId) {
		if (user == null)
			return null;
		return (List<MenuItem>) com.css.db.memcached.MemCachedFactory.get(getUserKey(user, sysId));
	}

	/**
	 * 缓存用户菜单
	 * 
	 * @return
	 */
	private void cacheListItem(IUser user, String sysId, List<MenuItem> items) {
		if (items == null)
			return;
		if (user == null)
			return;
		com.css.db.memcached.MemCachedFactory.set(getUserKey(user, sysId), items, ConfigurationManager.getCacheTime());
	}

	/**
	 * 返回用户缓存键值
	 * 
	 * @param user
	 * @return
	 */
	private String getUserKey(IUser user, String sysId) {
		return cacheName + "/" + sysId + "/" + user.getUserId();
	}
}
